package com.buba.system.Filter;

import com.alibaba.fastjson.JSON;
import com.buba.system.pojo.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter("/MenuServlet")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //请求和响应强转成http
        HttpServletRequest req = (HttpServletRequest) servletRequest ;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取会话作用域的登录用户信息
        HttpSession session = req.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("login");
        if (userInfo == null){
            Map<String, Object> map = new HashMap<>();
            map.put("message","no");
            resp.getWriter().write(JSON.toJSONString(map));
        }else{
            filterChain.doFilter(req, resp);
        }
    }
}
